package base

type BytecodeReader struct {
	code []byte //字节码
	pc   int    //读取指针
}

func (e *BytecodeReader) Reset(code []byte, pc int) {
	e.code = code
	e.pc = pc
}

func (e *BytecodeReader) PC() int {
	return e.pc
}

func (e *BytecodeReader) ReadUint8() uint8 {
	i := e.code[e.pc]
	e.pc++
	return i
}

func (e *BytecodeReader) ReadInt8() int8 {
	return int8(e.ReadUint8())
}

func (e *BytecodeReader) ReadUint16() uint16 {
	byte1 := uint16(e.ReadUint8())
	byte2 := uint16(e.ReadUint8())
	return (byte1 << 8) | byte2
}

func (e *BytecodeReader) ReadInt16() int16 {
	return int16(e.ReadUint16())
}

func (e *BytecodeReader) ReadInt32() int32 {
	byte1 := int32(e.ReadUint8())
	byte2 := int32(e.ReadUint8())
	byte3 := int32(e.ReadUint8())
	byte4 := int32(e.ReadUint8())
	return (byte1 << 24) | (byte2 << 16) | (byte3 << 8) | byte4
}

// ReadInt32s used by lookupswitch and tableswitch
func (e *BytecodeReader) ReadInt32s(n int32) []int32 {
	its := make([]int32, n)
	for i := range its {
		its[i] = e.ReadInt32()
	}
	return its
}

// SkipPadding used by lookupswitch and tableswitch
func (e *BytecodeReader) SkipPadding() {
	for e.pc%4 != 0 {
		e.ReadUint8()
	}
}
